package com.ljfiction.book.tools;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AppOpsManager;
import android.app.DatePickerDialog;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.provider.Settings;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.DatePicker;
import android.widget.TextView;
import android.widget.Toast;


import com.google.gson.Gson;
import com.ljfiction.book.R;
import com.ljfiction.book.activitys.BaseActivity;
import com.ljfiction.book.http.HttpManager;
import com.lzy.okhttputils.OkHttpUtils;
import com.lzy.okhttputils.callback.StringCallback;

import org.json.JSONObject;

import java.io.File;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.text.DecimalFormat;
import java.util.UUID;

import okhttp3.Call;
import okhttp3.Response;

import static android.content.Context.INPUT_METHOD_SERVICE;


/**
 * Created by Administrator on 2016/5/23.
 */
public class Tool {
    /**
     * 判断是否开启了自动亮度调节
     *
     * @param aContentResolver
     * @return
     */
    public static Context context1;
    public static boolean isAutoBrightness(ContentResolver aContentResolver) {
        boolean automicBrightness = false;
        try {
            automicBrightness = Settings.System.getInt(aContentResolver,
                    Settings.System.SCREEN_BRIGHTNESS_MODE) == Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC;
        } catch (Settings.SettingNotFoundException e) {
            e.printStackTrace();
        }
        return automicBrightness;
    }

    /**
     * 获取屏幕的亮度
     *
     * @param activity
     * @return
     */
    public static int getScreenBrightness(Activity activity) {
        int nowBrightnessValue = 0;
        ContentResolver resolver = activity.getContentResolver();
        try {
            nowBrightnessValue = Settings.System.getInt(
                    resolver, Settings.System.SCREEN_BRIGHTNESS);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return nowBrightnessValue;
    }

    /**
     * 设置亮度
     *
     * @param activity
     * @param brightness
     */
    public static void setBrightness(Activity activity, int brightness) {
        // Settings.System.putInt(activity.getContentResolver(),
        // Settings.System.SCREEN_BRIGHTNESS_MODE,
        // Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL);
        WindowManager.LayoutParams lp = activity.getWindow().getAttributes();
        lp.screenBrightness = Float.valueOf(brightness) * (1f / 255f);
        activity.getWindow().setAttributes(lp);
    }

    /**
     * 停止自动亮度调节
     *
     * @param activity
     */
    public static void stopAutoBrightness(Activity activity) {
        Settings.System.putInt(activity.getContentResolver(),
                Settings.System.SCREEN_BRIGHTNESS,
                Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL);
    }

    /**
     * 开启亮度自动调节
     *
     * @param activity
     */
    public static void startAutoBrightness(Activity activity) {
        Settings.System.putInt(activity.getContentResolver(),
                Settings.System.SCREEN_BRIGHTNESS_MODE,
                Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC);
    }

    /**
     * 保存亮度设置状态
     *
     * @param resolver
     * @param brightness
     */
    public static void saveBrightness(ContentResolver resolver, int brightness) {
        Uri uri = Settings.System
                .getUriFor("screen_brightness");
        Settings.System.putInt(resolver, "screen_brightness",
                brightness);
        resolver.notifyChange(uri, null);
    }
    public interface TimeDialogListener{
        public void back(String str);
    }
    public static void showTimeDialog(final BaseActivity context, final TextView textView, final  int mYear, final  int mMonth, final int mDay, final TimeDialogListener ... listeners){
        new DatePickerDialog(context, new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker view, int year, int monthOfYear,int dayOfMonth) {

                String str="";
                /*if (year>mYear) {
                    context.showToast("日期不能超过今天");
                    return;
                }else if(year==mYear&&monthOfYear>mMonth){
                    context.showToast("日期不能超过今天");
                    return;
                }else if (year==mYear&&monthOfYear==mMonth&&dayOfMonth>mDay) {
                    context.showToast("日期不能超过今天");
                    return;
                }*/
                if (monthOfYear<10) {
                    if (dayOfMonth<10) {
                        str=year+"-0"+(monthOfYear+1)+"-0"+dayOfMonth;
                    }else {
                        str=year+"-0"+(monthOfYear+1)+"-"+dayOfMonth;
                    }
                }else {
                    str=year+"-"+(monthOfYear+1)+"-"+dayOfMonth;

                }
                textView.setText(str);
                if (listeners.length>0&&listeners[0]!=null){
                    listeners[0].back(str);
                }
            }
        }, mYear, mMonth, mDay).show();
    }

    /**
     * 换算长度千米KM
     * @param mi 单位为米的数字不需要带单位 不能为负数
     * @return
     */
    public static String conversionUnit(String mi){
        double original=Double.parseDouble(mi);
        double newret=Double.parseDouble(mi);
        String unit="km";
        newret=original/1000;
        unit="km";
        DecimalFormat df = new DecimalFormat("#0.00");
        return df.format(newret)+unit;

    }
    /**
     * 换算长度 0~1结果为厘米CM   1~1000结果为米M   1000~1000000结果为千米KM
     * @param mi 单位为米的数字不需要带单位 不能为负数
     * @return
     */
    public static String conversionUnit1(String mi){
        double original=Double.parseDouble(mi);
        double newret=Double.parseDouble(mi);
        String unit="m";
        if (original<1) {
            newret=original*100;
            unit="cm";
        }else if (original<1000) {
            newret=original;
            unit="m";
        }
        else if (original>=1000) {
            newret=original/1000;
            unit="km";
        }
        DecimalFormat df = new DecimalFormat("#0.0");
        return df.format(newret)+unit;

    }
    /**
     * 获取版本号
     * @return 当前应用的版本号
     */
    public static String getVersion(Context context) {
        try {
            PackageManager manager = context.getPackageManager();
            PackageInfo info = manager.getPackageInfo(context.getPackageName(), 0);
            String version = info.versionName;
            return  version;
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }
    /**
     * 获取版本号
     *
     * @return 当前应用的版本号
     */
    public static int getVersion(Context context,int defaul) {
        try {
            PackageManager manager = context.getPackageManager();
            PackageInfo info = manager.getPackageInfo(context.getPackageName(),0);
            int version = info.versionCode;
            return version;
        } catch (Exception e) {
            e.printStackTrace();
            return defaul;
        }
    }

   /* static Toast toast;
    static View layout;
    static TextView text;
    //
    static Toast toast1;
    static View layout1;
    static Toast toast2;
    static View layout2;*/
    public static void zidongbancuntishi(Context context) {

        //
         Toast toast1;
         View layout1;
         Toast toast2 = null;
         View layout2 = null;
        if (toast2==null) {
            LayoutInflater inflater = LayoutInflater.from(context);
            layout2 = inflater.inflate(R.layout.zidongbaocuntishi, null);
            toast2 = new Toast(context);
            toast2.setGravity(Gravity.TOP|Gravity.CENTER_HORIZONTAL, 0,0);
            layout2.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);//设置Toast可以布局到系统状态栏的下面
            toast2.setDuration(Toast.LENGTH_SHORT);
            toast2.setView(layout2);
            toast2.show();
        }else {
            toast2.setView(layout2);
            toast2.show();
        }
    }
    public static void xmjaddtishi(Context context) {

        Toast toast1 = null;
         View layout1 = null;
        context1=context.getApplicationContext();
        if (toast1==null) {
        LayoutInflater inflater = LayoutInflater.from(context);
        layout1 = inflater.inflate(R.layout.addlajiao, null);
        toast1 = new Toast(context);
        toast1.setGravity(Gravity.CENTER, 0, 0);
        toast1.setDuration(Toast.LENGTH_SHORT);
        toast1.setView(layout1);
        toast1.show();
        }else {
            toast1.setView(layout1);
            toast1.show();
        }
    }
 private static    Toast toast = null;
    private static   View layout = null;
    private static  TextView text = null;
    public static void showToast(String msg,Context context) {

        if (toast==null) {
            LayoutInflater inflater = LayoutInflater.from(context);
            layout = inflater.inflate(R.layout.toast, null);
            text =(TextView) layout.findViewById(R.id.toastTV);
            text.setText(msg);
            toast = new Toast(context);
            toast.setGravity(Gravity.CENTER, 0, 80);
            toast.setDuration(Toast.LENGTH_SHORT);
            toast.setView(layout);
            toast.show();
        }else {
            text.setText(msg);
            toast.setView(layout);
            toast.show();
        }
    }

    /**
     * 计算文件夹大小
     * @param file
     * @return
     */
    public static double getDirSize(File file) {
        //判断文件是否存在
        if (file.exists()) {
            DecimalFormat df = new DecimalFormat("#0.0");
            //如果是目录则递归计算其内容的总大小
            if (file.isDirectory()) {
                File[] children = file.listFiles();
                double size = 0;
                for (File f : children)
                    size += getDirSize(f);
                return Double.valueOf(df.format(size));
            } else {//如果是文件则直接返回其大小,以“兆”为单位
                double size = (double) file.length() / 1024 / 1024;
                return Double.valueOf(df.format(size));
            }
        } else {

            return 0.0;
        }
    }
    /**
     * 计算文件夹大小
     * @param path
     * @return
     */
    public static double getDirSize(String path) {
        File file =new File(path);
       return getDirSize(file);
    }
    /*
    * 隐藏软键盘
    *
    * */
    public static void hideKeybard(Activity activity){
        ((InputMethodManager)activity.getSystemService(INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
    }
    /*
    * 是否开启通知权限
    * */
    @SuppressLint("NewApi")
    public static boolean isNotificationEnabled(Context context) {

        AppOpsManager mAppOps = (AppOpsManager) context.getSystemService(Context.APP_OPS_SERVICE);
        ApplicationInfo appInfo = context.getApplicationInfo();
        String pkg = context.getApplicationContext().getPackageName();
        int uid = appInfo.uid;

        Class appOpsClass = null;
      /* Context.APP_OPS_MANAGER */
        try {
            appOpsClass = Class.forName(AppOpsManager.class.getName());
            Method checkOpNoThrowMethod = appOpsClass.getMethod("checkOpNoThrow", Integer.TYPE, Integer.TYPE,
                    String.class);
            Field opPostNotificationValue = appOpsClass.getDeclaredField("OP_POST_NOTIFICATION");

            int value = (Integer) opPostNotificationValue.get(Integer.class);
            return ((Integer) checkOpNoThrowMethod.invoke(mAppOps, value, uid, pkg) == AppOpsManager.MODE_ALLOWED);

        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return false;
    }
/*
*进入系统设置界面
 */
    protected void requestPermission(int requestCode,Activity activity) {
        // 6.0以上系统才可以判断权限

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.BASE) {
            // 进入设置系统应用权限界面
            Intent intent = new Intent(Settings.ACTION_SETTINGS);
            activity.startActivity(intent);
            return;
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {// 运行系统在5.x环境使用
            // 进入设置系统应用权限界面
            Intent intent = new Intent(Settings.ACTION_SETTINGS);
            activity.startActivity(intent);
            return;
        }
        return;
    }

}
